import router from '@/router'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useUserStore, useRouteStore } from '@/store'
import type { RouteRecordRaw } from 'vue-router'
// import { getToken } from '@/utils/auth'

NProgress.configure({ showSpinner: false })
const whiteList = ['/login', '/redirect']

/** 是否已经生成过路由表 */
let hasMenu = false
export const resetHasMenu = () => {
  hasMenu = false
}

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const userStore = useUserStore()
  const routeStore = useRouteStore()
  const hasToken = userStore.token
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/', replace: true })
    } else {
      if (!hasMenu) {
        try {
          const accessRoutes = await routeStore.generateRoutes()
          accessRoutes.forEach((route: RouteRecordRaw) => {
            router.addRoute('layout', route) // 动态添加可访问路由表
          })
          hasMenu = true
          next({ ...to, replace: true }) // // 这里相当于push到一个页面 不在进入路由拦截
        } catch (error: any) {
          userStore.logout()
          ElMessage.error(error.message || '路由守卫过程发生错误')
          next(`/login?redirect=${to.path}`)
        }
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // ElMessage.error('登錄過期，請重新登錄')
      await userStore.logout()
      next(`/login?redirect=${to.path}`)
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
